package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Doctor;
import com.example.demo.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    private DoctorService doctorService;

    // 分页获取医生列表
    @GetMapping
    public IPage<Doctor> listAllDoctors(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {
        return doctorService.page(new Page<>(page, size));
    }

    // 模糊查询医生（职称和简介），分页
    @GetMapping("/search")
    public IPage<Doctor> searchDoctors(
            @RequestParam("keyword") String keyword,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {
        QueryWrapper<Doctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", keyword).or().like("intro", keyword);
        return doctorService.page(new Page<>(page, size), queryWrapper);
    }

    // 新增医生
    @PostMapping("/add")
    public boolean addDoctor(@RequestBody Doctor doctor) {
        try {
            return doctorService.save(doctor);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 修改医生
    @PostMapping("/update")
    public boolean updateDoctor(@RequestBody Doctor doctor) {
        return doctorService.updateById(doctor);
    }

    // 删除医生
    @DeleteMapping("/delete/{id}")
    public boolean deleteDoctor(@PathVariable Integer id) {
        return doctorService.removeById(id);
    }
}
